package menu

import (
	"context"
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/constants"
	base2 "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/base"
	pb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/base"
)

type menuRepository struct {
}

// NewMenuRepository 构造展示
func NewMenuRepository() MenuRepositoryIface {
	return &menuRepository{}
}

// MenuList 菜单列表
func (r *menuRepository) MenuList(ctx context.Context, getVisibleMenu int64) ([]*base2.MenuItem, error) {
	req := &pb.MenuListRequest{OnlyCurrentUser: getVisibleMenu}
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewBaseMenuServiceClient(conn)
	resp, err := client.MenuList(ctx, req)
	if err != nil {
		return nil, err
	}
	list := make([]*base2.MenuItem, 0)
	for _, item := range resp.List {
		pList := make([]*base2.PermissionItem, 0)
		if item.PermissionList != nil {
			for _, pItem := range item.PermissionList {
				pList = append(pList, &base2.PermissionItem{
					Id:     pItem.Id,
					Name:   pItem.Name,
					Type:   pItem.Type,
					MenuId: pItem.MenuId,
				})
			}
		}

		list = append(list, &base2.MenuItem{
			Id:             item.Id,
			Name:           item.Name,
			ParentId:       item.ParentId,
			Icon:           item.Icon,
			Path:           item.Path,
			UrlType:        item.UrlType,
			Url:            item.Url,
			Sort:           item.Sort,
			IsLeaf:         item.IsLeaf,
			PermissionList: pList,
			IsSelected:     item.IsSelected,
			Extend:         item.Extend,
		})
	}

	return list, nil
}
